package grid;

import java.util.ArrayList;


public abstract class AbstractGridFactory implements GridFactory {

	private Grid grid;
	private ArrayList<GridFactoryListener> gridFactoryListenerList = new ArrayList<GridFactoryListener>();
	
	protected abstract Grid generateNewGrid();
	/* (non-Javadoc)
	 * @see grid.GridFactory#gridHasChanged()
	 */
	public abstract boolean gridHasChanged();
	
	@Override
	public boolean gridHasChanged(Grid grid) {
		return this.grid != grid || gridHasChanged();
	}

	/* (non-Javadoc)
	 * @see grid.GridFactory#generateGrid()
	 */
	@Override
	public synchronized Grid generateGrid(){
		if (gridHasChanged() || grid ==null) {
			this.grid = generateNewGrid();
		}
		return this.grid;
	}
	@Override
	public int countGridFactoryListener(){
		return gridFactoryListenerList.size();
	}
	
	protected void notifyGridFactoryListener(){
		for (GridFactoryListener listener : gridFactoryListenerList) {
			listener.gridChanged(this);
		}
	}
	
	
	
	
	/* (non-Javadoc)
	 * @see grid.GridFactory#addGridFactoryListener(grid.GridFactoryListener)
	 */
	@Override
	public synchronized void addGridFactoryListener(GridFactoryListener listener){
		gridFactoryListenerList.add(listener);
	}
	
	/* (non-Javadoc)
	 * @see grid.GridFactory#removeGridFactoryListener(grid.GridFactoryListener)
	 */
	@Override
	public void removeGridFactoryListener(GridFactoryListener listener) {
		gridFactoryListenerList.remove(listener);
	}
}
